/*
 * pit.c
 * Project 4
 * Nicole Ang (nang1@asu.edu)
 * Bijan Fakhri (bfakhri@asu.edu)
 * CSE 325: Embedded Microprocessor Systems
 * Spring 2013
 */

#include "pit.h"

int currentTempo;

void pit0_init(){
	//disable while configuring
	MCF_PIT0_PCSR &= ~MCF_PIT_PCSR_EN;
	
	//reload counter when it reaches 0
	MCF_PIT0_PCSR |= MCF_PIT_PCSR_RLD;
	
	//reset interrupt flag
	MCF_PIT0_PCSR |= MCF_PIT_PCSR_PIF;
	
	//enable PIF flag to generate interrupt requests
	MCF_PIT0_PCSR |= MCF_PIT_PCSR_PIE;
	
	//immediately overwrite value in PIT counter
	MCF_PIT0_PCSR |= MCF_PIT_PCSR_OVW;
	
	//stop PIT funciton in debug mode
	MCF_PIT0_PCSR |= MCF_PIT_PCSR_DBG;
	
	//set prescaler
	MCF_PIT0_PCSR |= MCF_PIT_PCSR_PRE(13);
	
	//Initially set timeout period to 1 sec = 60 BPM.
	currentTempo = 60;
	setTempo(60);
	
	//configure INTC to recognize & respond to interrupt requests
	intcr_config(55, 1, 7, pit0_isr);
	
	//enable
	MCF_PIT0_PCSR |= MCF_PIT_PCSR_EN;
}

__declspec(interrupt) void pit0_isr(){
	/* Clear interrupt request flag. */
	MCF_PIT0_PCSR |= MCF_PIT_PCSR_PIF;

	/* Do whatever you need to do to service the PIT0. */
	playNextNote();
}

void setTempo(int newBeat){
	//set value of counter
	switch(newBeat){
	/*case 60: MCF_PIT0_PMR = 4881;
		currentTempo = 60;
		break;*/
	case 70: MCF_PIT0_PMR = 1045;
		currentTempo = 70;
		break;
	case 80: MCF_PIT0_PMR = 914;
		currentTempo = 80;
		break;
	case 90: MCF_PIT0_PMR = 813;
		currentTempo = 90;
		break;
	case 100: MCF_PIT0_PMR = 731;
		currentTempo = 100;		
		break;	
	case 110: MCF_PIT0_PMR = 664;
		currentTempo = 110;
		break;
	case 120: MCF_PIT0_PMR = 609;
		currentTempo = 120;
		break;
	default: MCF_PIT0_PMR = 4881;
		currentTempo = 60;
		break;
	}
}

void setDuration(Type noteType){
	int counter = MCF_PIT0_PMR;
	switch(noteType){
	case whole: counter = counter * 4;
		break;
	case half_dot: counter = counter * 3;
		break;
	case half: counter = counter * 2;
		break;
	//case quarter_dot: counter = counter * 1.5;
		//break;
	//case eigth_dot: counter = counter / ;
		//break;
	case eigth: counter = counter / 2;
		break;
	//case sixteenth_dot: counter = counter / ;
		//break;
	case sixteenth: counter = counter / 4;
		break;
	//case thirty_secondth_dot: counter = counter / ;
		//break;
	case thirty_secondth: counter = counter / 8;
		break;
	//case sixty_fourth_dot: counter = counter / ;
		//break;
	case sixty_fourth: counter = counter / 16;
		break;
	default: //quarter note, leave as is
		break;
	}
	
	//round counter down to an int, before assigning to PMR
}